import type { FormInstance } from 'element-plus'
import type { SystemDeptOptionsType, SystemDeptDataItemType } from './typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElButton,
  ElTreeSelect,
  ElIcon,
  ElMessage
} from 'element-plus'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim, traceToTreeData } from '~/utils/util'

export default defineComponent({
  name: 'SystemDeptOptions',
  props: ['visible', 'type', 'record', 'treeWordsListVlaue'],
  emits: ['cancel'],
  setup(props: SystemDeptOptionsType, { emit }) {
    const store = useStore()

    const ruleFormRef = ref<FormInstance>()
    const parentDeptDisabledRef = ref(false)
    const title = { add: '新增', update: '编辑', read: '查看', addSon: '新增子项' }

    const optionsValidateForm = reactive<SystemDeptDataItemType>(
      Object.assign(
        {
          deptName: '', // 部门名称
          fullName: '', // 部门全称
          parentId: '', // 上级部门
          sort: undefined, // 排序
          remark: '' // 备注
        },
        props.record
      )
    )

    // 新增子项 是否可填
    if (props.visible && props.type === 'addSon') {
      parentDeptDisabledRef.value = true // 上级部门
      optionsValidateForm.deptName = '' // 部门名称
      optionsValidateForm.parentId = optionsValidateForm.id
      optionsValidateForm.fullName = undefined // 部门全称
      optionsValidateForm.sort = undefined // 部门排序
      optionsValidateForm.remark = '' // 部门备注
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 提交
    const handleSubmitForm = () => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        if (props.type === 'addSon' && optionsValidateForm.id !== '') {
          delete optionsValidateForm.id
        }
        // 去输入的前后空格
        optionsValidateForm.deptName = handleTrim(optionsValidateForm.deptName ?? '')
        optionsValidateForm.fullName = handleTrim(optionsValidateForm.fullName ?? '')
        optionsValidateForm.remark = handleTrim(optionsValidateForm.remark ?? '')

        const params = { ...optionsValidateForm }
        const res = await store.dispatch('systemDept/PostSystemDeptSubmit', params) // 部门的 新增与编辑 为同一接口
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        } else {
          ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
        }
      })
    }

    return () => {
      const { type, visible } = props
      let treeWordsList = traceToTreeData(props.treeWordsListVlaue) // 上级部门 树id转字
      // 编辑 是否可填
      if (props.visible && props.type === 'update') {
        parentDeptDisabledRef.value = true // 上级部门
        treeWordsList = treeWordsList.concat([{ value: '0', label: '顶级' }])
      }

      return (
        <ElDialog
          title={(title[type!] as string) || '查看'}
          width={900}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <CirclePlus />
                    </ElIcon>
                    &nbsp; {type === 'update' ? '修改' : '保存'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>
                    <ElIcon>
                      <CircleClose />
                    </ElIcon>
                    取消
                  </ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={optionsValidateForm}>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="deptName"
                  label="部门名称"
                  rules={[{ required: true, message: '请输入 部门名称', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.deptName
                  ) : (
                    <ElInput
                      v-model={optionsValidateForm.deptName}
                      placeholder="请输入 部门名称"
                      clearable
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="fullName"
                  label="部门全称"
                  rules={[{ required: true, message: '请输入 部门全称', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.fullName
                  ) : (
                    <ElInput
                      v-model={optionsValidateForm.fullName}
                      placeholder="请输入 部门全称"
                      clearable
                    />
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="parentId"
                  label="上级部门"
                  rules={[{ required: true, message: '请选择 或输入关键字', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.parentName
                  ) : (
                    <ElTreeSelect
                      v-model={optionsValidateForm.parentId}
                      data={treeWordsList}
                      disabled={parentDeptDisabledRef.value}
                      placeholder="请选择 或输入关键字"
                      filterable
                      checkStrictly
                      clearable
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="sort"
                  label="部门排序"
                  rules={[{ required: true, message: '请输入 部门排序', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    optionsValidateForm.sort
                  ) : (
                    <ElInputNumber
                      v-model={optionsValidateForm.sort}
                      min={0}
                      controls-position="right"
                      placeholder="请输入 部门排序"
                    />
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol>
                <ElFormItem prop="remark" label="部门备注">
                  {type === 'read' ? (
                    optionsValidateForm.remark
                  ) : (
                    <ElInput
                      v-model={optionsValidateForm.remark}
                      placeholder="请输入 部门备注"
                      clearable
                    />
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
